const requestTaskMap = new Map(); // 请求任务集合

/**
 * @description 向请求任务集合添加对应的请求任务
 * @param {Object} config 请求任务的config
 * @param {Object} requestTask 请求任务
 */
export function addRequestTask(config = {}, requestTask = {}) {
  const pages = getCurrentPages(); // 获取页面栈
  const route = pages?.pop()?.route || ""; // 获取当前页路由
  // 处理json序列化会把undefined过滤掉的情况
  const configStr = JSON.stringify(
    {
      ...config,
      route,
    },
    (key, value) => (typeof value === "undefined" ? "" : value)
  );
  requestTaskMap.set(configStr, requestTask);
}

/**
 * @description 取消指定请求
 * @param {Object} config 要取消的请求的config
 */
export function removeCurrentRequestTask(config = {}) {
  const configList = Array.from(requestTaskMap.keys()).filter((item) => {
    const current = JSON.parse(item);
    return config.extra
      ? current.baseURL === config.baseURL &&
          current.url === config.url &&
          current.method === config.method &&
          current.extra === config.extra
      : current.baseURL === config.baseURL &&
          current.url === config.url &&
          current.method === config.method;
  });
  if (configList.length === 0) return;
  configList.forEach((item) => {
    requestTaskMap.get(item)?.abort();
    requestTaskMap.delete(item);
  });
}

/**
 * @description 取消当前路由下的指定请求
 * @param {Object} config 要取消的请求的config
 */
export function removeCurrentPageCurrentRequestTask(config = {}) {
  const pages = getCurrentPages(); // 获取页面栈
  const route = pages?.pop()?.route || ""; // 获取当前路由
  const configList = Array.from(requestTaskMap.keys()).filter((item) => {
    const current = JSON.parse(item);
    return config.extra
      ? current.baseURL === config.baseURL &&
          current.url === config.url &&
          current.method === config.method &&
          current.route === route &&
          current.extra === config.extra
      : current.baseURL === config.baseURL &&
          current.url === config.url &&
          current.method === config.method &&
          current.route === route;
  });
  if (configList.length === 0) return;
  configList.forEach((item) => {
    requestTaskMap.get(item)?.abort();
    requestTaskMap.delete(item);
  });
}

/**
 * @description 取消当前路由下的所有请求
 */
export function removeCurrentPageAllRequestTask() {
  const pages = getCurrentPages(); // 获取页面栈
  const route = pages?.pop()?.route || ""; // 获取当前路由
  const configList = Array.from(requestTaskMap.keys()).filter((item) => {
    const current = JSON.parse(item);
    return current.route === route;
  });
  if (configList.length === 0) return;
  configList.forEach((item) => {
    requestTaskMap.get(item)?.abort();
    requestTaskMap.delete(item);
  });
}

/**
 * @description 清空请求任务集合，并取消里面所有的请求
 */
export function clearRequestTask() {
  for (const [, requestTask] of requestTaskMap) {
    requestTask.abort();
  }
  requestTaskMap.clear();
}
